package com.ftj.bills.sys.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ftj.bills.common.DataGridView;
import com.ftj.bills.common.ResultObj;
import com.ftj.bills.sys.pojo.Bills;
import com.ftj.bills.sys.pojo.Billtype;
import com.ftj.bills.sys.service.BillsService;
import com.ftj.bills.sys.service.BilltypeService;
import com.ftj.bills.sys.vo.BillsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author 21seu.ftj
 */
@Controller
@RequestMapping("/bills")
public class BillsController {

    @Autowired
    private BillsService billsService;
    @Autowired
    private BilltypeService billtypeService;

    @RequestMapping("/toList")
    public String toListPage() {
        return "list";
    }

    @RequestMapping("/loadAllBills")
    @ResponseBody
    public DataGridView loadAllBills(BillsVo billsVo) {
        IPage<Bills> page = new Page<>(billsVo.getPage(), billsVo.getLimit());
        QueryWrapper<Bills> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != billsVo.getTypeid() && billsVo.getTypeid() != 0, "typeid", billsVo.getTypeid());
        queryWrapper.ge(billsVo.getStartDate() != null, "billtime", billsVo.getStartDate());
        queryWrapper.le(billsVo.getEndDate() != null, "billtime", billsVo.getEndDate());
        queryWrapper.orderByDesc("billtime");
        billsService.page(page, queryWrapper);

        List<Bills> records = page.getRecords();
        for (Bills record : records) {
            Billtype billtype = this.billtypeService.getById(record.getTypeid());
            record.setTypeName(billtype.getName());
        }
        return new DataGridView(page.getTotal(), records);
    }

    /**
     * 添加账单
     * @param billsVo
     * @return
     */
    @RequestMapping("/addBills")
    @ResponseBody
    public ResultObj addBills(BillsVo billsVo) {
        try {
            this.billsService.save(billsVo);
            return new ResultObj(200, "录入成功");
        } catch (Exception e) {
            return new ResultObj(-1, "录入失败");
        }
    }
}
